﻿using System;
using System.Web;
using gms.data;
using gms.system;

namespace gms.security {
	public static class Authentication {
		public static int AuthedPlayer {
			get {
				if (SessionKeyExists("player_id")) {
					return int.Parse(HttpContext.Current.Session["player_id"].ToString());
				}
				else {
					return -1;
				}
			}
			set {
				HttpContext.Current.Session["player_id"] = value;
			}
		}
		public static string AuthedIP {
			get {
				return HttpContext.Current.Request.UserHostAddress;
			}
		}
		public static bool IsSessionAuthed() {
			bool retval = false;
			Player login = Player.load_by_id(AuthedPlayer);

			if (login != null) {
				if (login.address.Equals(AuthedIP)) {
					retval = true;
				}
				else {
					ClearSession();
				}
			}
			else {
				ClearSession();
			}

			return retval;
		}
		public static bool IsValidLogin(string mail, string pass) {
			bool retval = true;

			Player login = Player.load_by_email(mail);
			byte[] login_pass;

			if (login == null) {
				retval = false;
			}

			if (retval) {
				login_pass = Hashing.get_password_hash(pass, login.salt);

				string output = "";
				for (int i = 0; i < login_pass.Length; i++) {
					output += login_pass[i].ToString();
				}

				if (!Hashing.bytes_are_same(login_pass, login.password)) {
					retval = false;
				}
			}

			return retval;
		}
		public static void ClearSession() {
			HttpContext.Current.Session.Clear();
		}
		public static void MustBeAuthed() {
			if (!IsSessionAuthed()) {
				HttpContext.Current.Response.Redirect("/login.aspx");
			}
		}
		private static bool SessionKeyExists(string key) {
			bool retval = false;

			if (HttpContext.Current.Session != null) {
				foreach (string local_key in HttpContext.Current.Session.Keys) {
					if (local_key.Equals(key)) {
						retval = true;
					}
				}
			}

			return retval;
		}
	}
}